package com.alisls.activiti.service.security;

import com.alisls.activiti.service.util.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 当未认证的情况下请求接口会响应302，但是前端无法处理，
 * 于是我们响应一个正常的JSON字符串，其中code为50008，前端收到这个请求后跳转到登录页
 *
 * @author Ke Wang
 */
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Resource
    private ObjectMapper objectMapper;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
            throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        String json = objectMapper.writeValueAsString(Result.build(50008, "请登录后访问"));
        response.getWriter().write(json);
    }

}
